﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using GestionDeCinebox.Classes;
using System.Data.SqlClient;
using System.Data;

namespace GestionDeCinebox
{
    /// <summary>
    /// Interaction logic for Reservation.xaml
    /// </summary>
    public partial class Reservation : Window
    {
        private Film f;
        private List<Image> listChaise;
        private List<Salle> listSalle;
        private List<Calendrier> listCalen;
        private List<TypeDeBillet> listType;
        private List<Billet> listBillet;
        private String idSalle = null;
        private String idCalen = null;
        private String idType = null;
        private String numChaise;
        private String idB = "";
        private String nomSalle;

        public Reservation(Film f)
        {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            this.f = f;
            listSalle = new List<Salle>();
            listChaise = new List<Image>();
            listCalen = new List<Calendrier>();
            listType = new List<TypeDeBillet>();
            listBillet = new List<Billet>();

            LoadViewContent();
            GetListCalen();
        }
        #region Method
        //code here
        void GetListCalen()
        {
            if (listCalen.Count > 0)
            {
                listCalen.Clear();
            }
            using (SqlCommand command = new SqlCommand("dbo.spDonnerLaListeCalenDeIDFilm"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;
                command.Parameters.Add(new SqlParameter("@idfilm", f.IdFilm));

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Calendrier c = new Calendrier();
                        c.IdCal = reader.GetString(reader.GetOrdinal("IDCalendrier"));
                        c.IdFilm = reader.GetString(reader.GetOrdinal("IDFilm"));
                        c.Temps = reader.GetDateTime(reader.GetOrdinal("Temps")).ToShortTimeString();
                        bool exists = false;
                        for (int i = 0; i < listCalen.Count; i++ )
                        {
                            if (c.Temps.Equals(listCalen[i].Temps))
                            {
                                exists = true;
                                break;
                            }
                        }
                        if (!exists)
                        {
                            listCalen.Add(c);
                        }
                    }
                }
            }
        }

        void GetListChaiseFromSalle(String nomSalle)
        {
            //get list billet
            int nombreBillet = 0;
            using (SqlCommand command = new SqlCommand("dbo.spDonnerNombreDeBilleDansSalle"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;
                command.Parameters.Add(new SqlParameter("@nomdesalle", nomSalle));

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        nombreBillet = reader.GetInt32(reader.GetOrdinal("NombreBillet"));
                    }
                }
            }
            //show chaise
            ShowListChaise(nomSalle, nombreBillet);
        }

        void GetListSalle()
        {
            if (listSalle.Count > 0)
            {
                listSalle.Clear();
            }
            if (lstSalle.Items.Count > 0)
            {
                lstSalle.Items.Clear();
            }
            using (SqlCommand command = new SqlCommand("dbo.spDonnerLaListeDuSalle"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Salle s = new Salle();
                        s.IdSalle = reader.GetString(reader.GetOrdinal("IDSalle"));
                        int n = reader.GetInt32(reader.GetOrdinal("NombreBillet"));
                        s.NombreDeBillet = n.ToString();
                        s.NomDeSalle = reader.GetString(reader.GetOrdinal("NomdeSalle"));
                        listSalle.Add(s);

                        StackPanel spSalle = new StackPanel();
                        spCalen.HorizontalAlignment = HorizontalAlignment.Center;
                        Image b = new Image();
                        b.Width = 70;
                        b.Height = 70;
                        b.Margin = new Thickness(0, 0, 6, 0);
                        b.Source = new BitmapImage(new Uri("/Images/salle1.png", UriKind.Relative));
                        b.Name = "btn" + (listSalle.Count - 1).ToString();
                        b.MouseLeftButtonDown += new MouseButtonEventHandler(bSalleClick);
                        b.MouseEnter += new MouseEventHandler(bSalleMouseEnter);
                        b.MouseLeave += new MouseEventHandler(bSalleMouseLeave);
                        b.Cursor = Cursors.Hand;
                        TextBlock nameSalle = new TextBlock();
                        nameSalle.Text = s.NomDeSalle;
                        nameSalle.Margin = new Thickness(24, 0, 0, 0);

                        spSalle.Children.Add(b);
                        spSalle.Children.Add(nameSalle);
                        lstSalle.Items.Add(spSalle);
                    }
                }
            }
        }

        void GetIDBillet(String numChaise, String idType, String idCalen, String idSalle)
        {
            using (SqlCommand command = new SqlCommand("dbo.spDonnerIDBillet"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;
                command.Parameters.Add(new SqlParameter("@numChaise", numChaise));
                command.Parameters.Add(new SqlParameter("@idTypeDeBillet", idType));
                command.Parameters.Add(new SqlParameter("@idcalen", idCalen));
                command.Parameters.Add(new SqlParameter("@idSalle", idSalle));

                using(SqlDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read())
                    {
                        idB = reader.GetString(reader.GetOrdinal("IDBillet"));
                    }
                }
            }
        }

        void GetAllBillet()
        {
            if (listBillet.Count > 0)
            {
                listBillet.Clear();
            }
            using (SqlCommand command = new SqlCommand("dbo.sp_LayTatCaVe"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Billet b = new Billet();
                        b.IdBillet = reader.GetString(reader.GetOrdinal("IDBillet"));
                        b.IdCalendrier = reader.GetString(reader.GetOrdinal("IDCalendrier"));
                        b.IdSalle = reader.GetString(reader.GetOrdinal("IDSalle"));
                        b.IdTypeDeBillet = reader.GetString(reader.GetOrdinal("IDTypeDeBillet"));
                        b.NumChaise = reader.GetString(reader.GetOrdinal("NumChaise"));

                        listBillet.Add(b);
                    }
                }
            }
        }

        void ShowListCalen()
        {
            if (spCalen.Children.Count > 0)
            {
                spCalen.Children.Clear();
            }
            for (int i = 0; i < listCalen.Count; i++ )
            {
                Button b = new Button();
                b.Name = "btn" + i.ToString();
                b.Content = listCalen[i].Temps;
                b.Margin = new Thickness(6,0,0,0);
                b.Width = 100;
                b.Click += new RoutedEventHandler(bCalenClick);

                spCalen.Children.Add(b);
            }
        }

        void ShowListChaise(String nomSalle, int n)
        {
            if (cvChaise.Children.Count > 0)
            {
                cvChaise.Children.Clear();
            }
            if(listChaise.Count > 0)
            {
                listChaise.Clear();
            }
            for (int i = 0; i < n; i++)
            {
                listChaise.Add(new Image());
            }

            int r = (int)cvChaise.Width;
            int d = (int)cvChaise.Height;

            int numCol = r / 60;
            int numRow = listChaise.Count / numCol + 1;
            if(60 * numRow > (int)cvChaise.Height)
            {
                cvChaise.Height = 60 * numRow + 30;
            }
            double left = 0;
            double top = 0;
            int index = 0;
            for (int i = 0; i < numRow; i++ )
            {
                top = 60 * i;
                for (int j = 0; j < numCol; j++ )
                {
                    if (i == numRow - 1 && j == listChaise.Count % numCol)
                    {
                        break;
                    }
                    left = 60 * j;

                    StackPanel spChaise = new StackPanel();
                    spChaise.SetValue(Canvas.LeftProperty, left);
                    spChaise.SetValue(Canvas.TopProperty, top);
                    listChaise[index].Width = 45;
                    listChaise[index].Height = 45;
                    listChaise[index].Source = new BitmapImage(new Uri("/Images/chaise1.png", UriKind.Relative));
                    listChaise[index].MouseEnter += new MouseEventHandler(bChaiseMouseEnter);
                    listChaise[index].MouseLeave += new MouseEventHandler(bChaiseMouseLeave);
                    listChaise[index].MouseLeftButtonDown += new MouseButtonEventHandler(buttonChaiseClick);
                    listChaise[index].Cursor = Cursors.Hand;
                    listChaise[index].Name = nomSalle + (index + 1).ToString("00");
                    TextBlock nameSalle = new TextBlock();
                    nameSalle.Text = nomSalle + (index + 1).ToString("00");
                    nameSalle.Margin = new Thickness(12, 0, 0, 0);
                    spChaise.Margin = new Thickness(6, 6, 0, 0);

                    spChaise.Children.Add(listChaise[index]);
                    spChaise.Children.Add(nameSalle);
                    cvChaise.Children.Add(spChaise);
                    
                    index++;
                }
            }
            SetStateChaise(nomSalle);
        }

        void SetStateChaise(String nomSalle)
        {
            GetAllBillet();
            for (int i = 0; i < listBillet.Count; i++ )
            {
                if (listBillet[i].NumChaise.StartsWith(nomSalle))
                {
                    for (int j = 0; j < listChaise.Count; j++ )
                    {
                        if (listChaise[j].Name == listBillet[i].NumChaise.Trim())
                        {
                            listChaise[j].Source = new BitmapImage(new Uri("/Images/checked.png", UriKind.Relative));
                            listChaise[j].IsEnabled = false;
                            break;
                        }
                    }
                }
            }
            for (int i = 0; i < listChaise.Count; i++ )
            {
                if (listChaise[i].IsEnabled == true)
                {
                    listChaise[i].Source = new BitmapImage(new Uri("/Images/chaise1.png", UriKind.Relative));
                    listChaise[i].IsEnabled = true;
                }
            }
        }

        void LoadViewContent()
        {
            img.Source = new BitmapImage(new Uri(f.Img, UriKind.Absolute));
            tbNom.Text = f.NomF;
            tbAuthor.Text = f.Author;
            tbActeur.Text = f.Acteurs;
            tbDuree.Text = f.Duree;
            tbLanguage.Text = f.Lang;
            tbType.Text = f.TypeF;
            tbInfo.Text = f.Info;

            GetListSalle();
        }

        void LoadTypeDeBillet()
        {
            if (cboType.Items.Count > 0)
            {
                cboType.Items.Clear();
            }
            using (SqlCommand command = new SqlCommand("dbo.spDonnerListeDuTypeBillet"))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Connection = DataProvider.Con;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        TypeDeBillet t = new TypeDeBillet();
                        t.Id = reader.GetString(reader.GetOrdinal("IDTypeDeBillet"));
                        t.NomDeType = reader.GetString(reader.GetOrdinal("NomdeType"));
                        t.Prix = reader.GetString(reader.GetOrdinal("Prix"));

                        listType.Add(t);
                        cboType.Items.Add(reader.GetString(reader.GetOrdinal("NomdeType")));
                    }
                }
            }
        }

        #endregion

        #region Event
        private void buttonChaiseClick(object sender, MouseButtonEventArgs e)
        {
            Image b = (Image)sender;
            numChaise = b.Name;

            //show reservation
            childReservation.Caption = "Inforamtion de Reservation - Chaise " + numChaise;
            ShowListCalen();
            LoadTypeDeBillet();
            childReservation.Show();
        }

        private void bCalenClick(object sender, RoutedEventArgs e)
        {
            Button b = (Button)sender;
            int index = Convert.ToInt32(b.Name.Substring(3));
            idCalen = listCalen[index].IdCal;
        }

        private void bSalleClick(object sender, MouseButtonEventArgs e)
        {
            Image i = (Image)sender;
            String s = i.Name;
            int index = Convert.ToInt32(s.Substring("btn".Length));

            idSalle = listSalle[index].IdSalle;
            nomSalle = listSalle[index].NomDeSalle;
            GetListChaiseFromSalle(nomSalle);
        }

        private void bSalleMouseEnter(object sender, MouseEventArgs e)
        {
            Image i = (Image)sender;
            i.Source = new BitmapImage(new Uri("/Images/salle2.png", UriKind.Relative));
        }
        private void bSalleMouseLeave(object sender, MouseEventArgs e)
        {
            Image i = (Image)sender;
            i.Source = new BitmapImage(new Uri("/Images/salle1.png", UriKind.Relative));
        }

        private void bChaiseMouseEnter(object sender, MouseEventArgs e)
        {
            Image i = (Image)sender;
            i.Source = new BitmapImage(new Uri("/Images/chaise2.png", UriKind.Relative));
        }
        private void bChaiseMouseLeave(object sender, MouseEventArgs e)
        {
            Image i = (Image)sender;
            i.Source = new BitmapImage(new Uri("/Images/chaise1.png", UriKind.Relative));
        }
        #endregion

        private void cboType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = cboType.SelectedIndex;
            if (i >= 0 && i < listType.Count)
            {
                idType = listType[i].Id;
            }
        }

        private void btnReserver_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MainWindow.personne == null)
                {
                    throw new Exception("Vous devez entrer en depart");
                }
                if (idCalen == null)
                {
                    throw new Exception("Vous devez choisir un calendrier");
                }
                if (idSalle == null)
                {
                    throw new Exception("Salle null");
                }
                if (idType == null)
                {
                    throw new Exception("Vous devez choisir un type de billet");
                }

                //insert billet
                try
                {
                    using (SqlCommand command = new SqlCommand("dbo.sp_ThemVe"))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Connection = DataProvider.Con;
                        command.Parameters.Add(new SqlParameter("@numChaise", numChaise));
                        command.Parameters.Add(new SqlParameter("@idTypeDeBillet", idType));
                        command.Parameters.Add(new SqlParameter("@idcalen", idCalen));
                        command.Parameters.Add(new SqlParameter("@idSalle", idSalle));

                        command.ExecuteNonQuery();
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                GetIDBillet(numChaise, idType, idCalen, idSalle);
                //reserver
                try
                {
                    using (SqlCommand command = new SqlCommand("dbo.sp_DatVe"))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Connection = DataProvider.Con;
                        command.Parameters.Add(new SqlParameter("@idMem", MainWindow.personne.Id));
                        command.Parameters.Add(new SqlParameter("@idBillet", idB));

                        command.ExecuteNonQuery();
                        MessageBox.Show("Succes");
                        childReservation.Close();
                        idB = "";
                        idCalen = null;
                        idType = null;
                        SetStateChaise(nomSalle);
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnAnnuler_Click(object sender, RoutedEventArgs e)
        {
            childReservation.Close();
            idB = "";
            idCalen = null;
            idType = null;
        }
    }
}
